/*
 * Accepter.cpp
 *
 *  Created on: 30/05/2011
 *      Author: dela
 */

#include "Accepter.h"

using namespace std;

/**
 *
 */
template <class T>
void Accepter<T>::run() {
	int newsockfd;

	while (isWorking()) {
		newsockfd = socket.acceptConnection();
		if (newsockfd > 0) {
			T *connection = new T(newsockfd);
			clearConnections();
			connections.push_back(connection);
			connection->start();
		}
		newsockfd = 0;
	}

}


/**
 *
 */
template <class T>
void Accepter<T>::clearConnections() {
	typedef list<T*> l;
	typedef typename l::iterator iterator;
	iterator it;
	if (connections.size() > 0) {
		it = connections.begin();
		while (connections.size() > 0 && it != connections.end()) {
			T *c = *it;
			if (!c->isWorking()) {
				c->connectionShutdown();
				c->join();
				delete c;
				connections.erase(it);
			} else
				it++;
		}
	}
}


/**
 *
 */
template <class T>
void Accepter<T>::stop() {
	setWorking(false);
	socket.shutdownSocket();
	if ( connections.size() > 0 ) {
		typedef list<T*> l;
		typedef typename l::iterator iterator;
		iterator it;
		for (it = connections.begin(); it != connections.end(); it++) {
			T *c = *it;
			c->connectionShutdown();
			c->join();
			delete c;
		}
	}
	this->join();
}
template void Accepter<InstructorConnection>::stop();
template void Accepter<StudentConnection>::stop();
